﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
using System.IO;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;




namespace MyMap
{
    public partial class MyMap : Form
    {
        public MyMap()
        {
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);  // 此代码不添加的话运行会有错误
            InitializeComponent();
        }

        private void MyMap_Load(object sender, EventArgs e)
        {
            axTOCControl1.SetBuddyControl(axMapControl1);
            // 初始化 DataGridView 样式
            dgvAttribute.ReadOnly = true;
            dgvAttribute.AllowUserToAddRows = false;
            dgvAttribute.AllowUserToDeleteRows = false;
        }

        

        private void AddVectorlayer(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "shapefile文件（*.shp）|*.shp";

            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            string path = openFileDialog.FileName;
            string folder = System.IO.Path.GetDirectoryName(path);
            string fileName = System.IO.Path.GetFileName(path);

            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace workspace = workspaceFactory.OpenFromFile(folder, 0);
            if (workspace == null)
            {
                MessageBox.Show("无法打开该工作空间！");
                return;
            }
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(fileName);
            if (featureClass == null)
            {
                MessageBox.Show("无法打开该矢量数据集！");
                return;
            }
            IFeatureLayer featureLayer = new FeatureLayerClass();
            featureLayer.FeatureClass = featureClass;
            featureLayer.Name = featureClass.AliasName;
            ILayer layer = featureLayer as ILayer;
            axMapControl1.Map.AddLayer(layer);
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

    

    private void AddRasterlayer(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            // 支持常见栅格格式：TIFF、JPG、PNG、BMP、GRID等
            openFileDialog.Filter = "栅格文件|*.tif;*.tiff;*.jpg;*.jpeg;*.png;*.bmp;*.img;*.grid|所有文件|*.*";

            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            string filePath = openFileDialog.FileName;
            string folderPath = System.IO.Path.GetDirectoryName(filePath);
            string fileName = System.IO.Path.GetFileName(filePath);

            try
            {
                // 创建栅格工作空间工厂
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace workspace = workspaceFactory.OpenFromFile(folderPath, 0);
                if (workspace == null)
                {
                    MessageBox.Show("无法打开栅格工作空间！");
                    return;
                }

                // 转换为栅格工作空间并打开栅格数据集
                IRasterWorkspace rasterWorkspace = workspace as IRasterWorkspace;
                IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(fileName);
                if (rasterDataset == null)
                {
                    MessageBox.Show("无法打开该栅格数据集！");
                    return;
                }

                // 创建栅格图层并设置属性
                IRasterLayer rasterLayer = new RasterLayerClass();
                rasterLayer.CreateFromDataset(rasterDataset);

                // 添加到地图控件并刷新视图
                ILayer layer = rasterLayer as ILayer;
                axMapControl1.Map.AddLayer(layer);
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加栅格图层失败：{ex.Message}");
            }
        }

        private void defineSimpleRender(IFeatureLayer featureLayer)
        {
            IRgbColor color = new RgbColor();
            color.Red = 255;
            color.Blue = 0;
            color.Green = 0;

            // 设置用于渲染的符号的基本属性（面状符号）
            ISimpleFillSymbol simpleFeatureSymbol = new SimpleFillSymbol();
            simpleFeatureSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
            simpleFeatureSymbol.Outline.Width = 0.4;
            simpleFeatureSymbol.Color = color as IColor;

            // 设置简单渲染的相关属性
            ISimpleRenderer simpleRenderer = new SimpleRendererClass();
            simpleRenderer.Symbol = simpleFeatureSymbol as ISymbol;

            // 接口转换，对渲染方式进行设置
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = simpleRenderer as IFeatureRenderer;

            // 地图刷新
            axMapControl1.Refresh();
        }

        private void Simplerendering(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index
            );

            if (tocChoosedLayer is IFeatureLayer)
            {
                defineSimpleRender(tocChoosedLayer as IFeatureLayer);
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void defineUniqueValueRender(IFeatureLayer featureLayer, string fieldName)
        {
            // 设置颜色列表，用于随机生成颜色（用于填充面状要素）
            // 设置颜色的基本属性，包括色调（H）、饱和度（S）以及亮度（V）
            IRandomColorRamp colorRamp = new RandomColorRamp();
            colorRamp.StartHue = 76;
            colorRamp.EndHue = 188;
            colorRamp.MinSaturation = 20;
            colorRamp.MaxSaturation = 40;
            colorRamp.MinValue = 85;
            colorRamp.MaxValue = 100;

            colorRamp.UseSeed = true;
            colorRamp.Seed = 43;

            // 设置唯一值渲染的相关属性
            IUniqueValueRenderer valueRender = new UniqueValueRenderer();
            valueRender.FieldCount = 1;
            valueRender.set_Field(0, fieldName);

            // 遍历要素类的所有要素，并为每个要素设置基本的渲染样式
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IFeatureCursor featureCursor = featureClass.Search(null, false);
            IFeature feature = featureCursor.NextFeature();

            // 获取指定字段的索引值
            IFields fields = featureCursor.Fields;
            // 存储字段的索引值
            int iFieldIndex = fields.FindField(fieldName);

            // 为不同的要素，设置不同的填充颜色
            colorRamp.Size = featureClass.FeatureCount(null);
            bool bOK;
            // 判断随机颜色生成是否成功
            colorRamp.CreateRamp(out bOK);

            // 获得随机生成的颜色列表
            IEnumColors enumColors = colorRamp.Colors;
            enumColors.Reset();
            IColor color = enumColors.Next();

            // 开始遍历，为每个要素设置基本的渲染信息
            while (feature != null)
            {
                // 为每个要素设置基本的渲染符号
                ISimpleFillSymbol simpleFillFeature = new SimpleFillSymbolClass();
                simpleFillFeature.Style = esriSimpleFillStyle.esriSFSSolid;
                simpleFillFeature.Outline.Width = 0.4;
                simpleFillFeature.Color = color;

                // 获得当前要素中指定字段的名称
                string featureName = Convert.ToString(feature.get_Value(iFieldIndex));

                // 设置唯一值渲染的相关属性
                valueRender.AddValue(featureName, fieldName, simpleFillFeature as ISymbol);
                valueRender.set_Label(featureName, featureName);
                valueRender.set_Symbol(featureName, simpleFillFeature as ISymbol);

                // 获得下一组要素和颜色
                feature = featureCursor.NextFeature();
                color = enumColors.Next();
            }

            // 接口转换，对渲染方式进行设置
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = valueRender as IFeatureRenderer;

            // 地图刷新
            axMapControl1.Refresh();
        }


        private void UniqueValueRendering(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index
            );

            if (tocChoosedLayer is IFeatureLayer)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(tocChoosedLayer as IFeatureLayer);
                DialogResult dialogResult = fieldSelectDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    defineUniqueValueRender(tocChoosedLayer as IFeatureLayer, fieldSelectDialog.selectFieldName());
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void ElementAttribute(object sender, EventArgs e)
        {
            esriTOCControlItem tocItem = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap basicMap = null;
            ILayer layer = null;
            object unk = null;
            object data = null;

            axTOCControl1.GetSelectedItem(ref tocItem, ref basicMap, ref layer, ref unk, ref data);

            if (tocItem == esriTOCControlItem.esriTOCControlItemLayer && layer is IFeatureLayer)
            {
                IFeatureLayer featureLayer = layer as IFeatureLayer;
                FeatureAttributeTable featureAttrTable = new FeatureAttributeTable(featureLayer);
                featureAttrTable.ShowDialog();
            }
            else
            {
                MessageBox.Show("请选择要素图层！");
            }
        }

        private void newMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            MyMxdDocClass myDoc = new MyMxdDocClass();
            myDoc.newMapDoc(axMapControl1); 
        }

        private void openMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            MyMxdDocClass myDoc = new MyMxdDocClass(); 
            myDoc.openMapDoc(axMapControl1); 
        }

        private void saveMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            MyMxdDocClass myDoc = new MyMxdDocClass(); 
            myDoc.saveMapDoc(axMapControl1); 
        }

        private void saveAsMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            MyMxdDocClass myDoc = new MyMxdDocClass(); 
            myDoc.SaveAsMapDoc(axMapControl1); 
        }

        private void AxTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            esriTOCControlItem tocControllerItem = esriTOCControlItem.esriTOCControlItemNone;
            ILayer layer = null;
            IBasicMap basicMap = null;
            object unk = null;
            object data = null;

            if (e.button == 1)
            { // 左键
                axTOCControl1.GetSelectedItem(
                    ref tocControllerItem,
                    ref basicMap,
                    ref layer,
                    ref unk,
                    ref data
                );

                if (tocControllerItem == esriTOCControlItem.esriTOCControlItemLegendClass)
                {
                    ESRI.ArcGIS.Carto.ILegendClass legendClass = new LegendClass();
                    ESRI.ArcGIS.Carto.ILegendGroup legendGroup = new LegendGroupClass();

                    if (unk is ILegendGroup)
                    {
                        legendGroup = unk as ILegendGroup;
                    }

                    legendClass = legendGroup.get_Class((int)data);
                    SymbolSelectDialog symbolSelectDilaog = new SymbolSelectDialog(legendClass, layer);
                    if (symbolSelectDilaog.ShowDialog() == DialogResult.OK)
                    {
                        legendClass.Symbol = symbolSelectDilaog.currentSymbol();
                        this.axMapControl1.ActiveView.Refresh();
                        this.axTOCControl1.Refresh();
                    }
                }
            }
        }

        private void AxMapControl1_OnAfterDraw(object sender, IMapControlEvents2_OnAfterDrawEvent e)
        {
            // 主地图有地图或图层的时候鹰眼图加载图层
            if (axMapControl1.LayerCount > 0)
            {
                // 先清除鹰眼图的地图
                axMapControlHawkeye.ClearLayers();

                // 图层自下而上加载，防止压盖顺序错误
                for (int i = axMapControl1.Map.LayerCount - 1; i >= 0; i--)
                {
                    axMapControlHawkeye.AddLayer(axMapControl1.get_Layer(i));
                }

                // 设置鹰眼地图与主地图相同空间参考系
                // 防止由于图层放置顺序改变而改变了鹰眼的空间参考系
                axMapControlHawkeye.SpatialReference = axMapControl1.SpatialReference;
                // 设置鹰眼的显示范围为完整显示（FullExtent）
                axMapControlHawkeye.Extent = axMapControlHawkeye.FullExtent;
                // 每次加载或删除图层之后都需要刷新鹰眼图
                axMapControlHawkeye.ActiveView.Refresh();
            }
        }

        private void AxMapControl1_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            // 得到新的范围
            IEnvelope envelop = e.newEnvelope as IEnvelope;
            IGraphicsContainer graphicsContainer = axMapControlHawkeye.Map as IGraphicsContainer;
            IActiveView activeView = graphicsContainer as IActiveView;

            // 在绘制前，清除鹰眼图中的任何图形元素
            graphicsContainer.DeleteAllElements();
            IRectangleElement rectangleElement = new RectangleElementClass();
            IElement element = rectangleElement as IElement;
            element.Geometry = envelop;

            // 设置鹰眼图中的红色线框
            IRgbColor frameColor = new RgbColorClass();
            frameColor.Red = 255;
            frameColor.Green = 0;
            frameColor.Blue = 0;
            frameColor.Transparency = 255;

            // 设置鹰眼图中的可视区域的填充颜色
            IRgbColor fillColor = new RgbColorClass();
            fillColor.Red = 255;
            fillColor.Green = 0;
            fillColor.Blue = 0;
            fillColor.Transparency = 0;

            // 产生一个线符号对象
            ILineSymbol outline = new SimpleLineSymbolClass();
            outline.Width = 2;
            outline.Color = frameColor;

            // 设置符号的填充属性
            IFillSymbol fillSymbol = new SimpleFillSymbolClass();
            fillSymbol.Color = fillColor;
            fillSymbol.Outline = outline;
            IFillShapeElement fillShapeElement = element as IFillShapeElement;
            fillShapeElement.Symbol = fillSymbol;
            graphicsContainer.AddElement((IElement)fillShapeElement, 0);

            // 刷新
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

        private void AxMapControlHawkeye_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (axMapControlHawkeye.LayerCount > 0)
            {

                // 如果是鼠标左键
                if (e.button == 1)
                {
                    axMapControlHawkeye.Refresh();
                    // 捕捉鼠标单击时的地图坐标
                    IPoint point = new PointClass();
                    point.PutCoords(e.mapX, e.mapY);
                    // 将地图的中心点移动到鼠标点击的点
                    axMapControl1.CenterAt(point);
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }
                else if (e.button == 2) // 如果是鼠标右键
                {
                    // 鹰眼地图的TrackRectAngle方法，随着鼠标的拖动得到一个矩形框
                    IEnvelope envelop = axMapControlHawkeye.TrackRectangle();
                    axMapControl1.Extent = envelop;
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                }

            }
        }

        private void AxMapControlHawkeye_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            // 如果是鼠标左键
            if (e.button == 1)
            {
                axMapControlHawkeye.Refresh();
                // 捕捉鼠标单击时的地图坐标
                IPoint point = new PointClass();
                point.PutCoords(e.mapX, e.mapY);
                // 将地图的中心点移动到鼠标点击的点
                axMapControl1.CenterAt(point);
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
        }

        private int m_iMouseFlag = 0;
        private string m_szFieldName = null;

        /// <summary>
        /// 根据屏幕像素计算实际的地理距离
        /// </summary>
        /// <param name="activeView">屏幕视图</param>
        /// <param name="pixelUnit">像素个数</param>
        /// <returns></returns>
        private double convertPixelToMapUnits(IActiveView activeView, double pixelUnits)
        {
            double realWorldDisplayExtent;
            int pixelExtent;
            double sizeOfOnePixel;
            double mapUnits;

            // 获取设备中视图显示宽度，即像素个数
            pixelExtent = activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().right
                - activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().left;
            // 获取地图坐标系中的地图显示范围
            realWorldDisplayExtent = activeView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width;
            // 每个像素大小代表的实际距离
            sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;
            // 地理距离
            mapUnits = pixelUnits * sizeOfOnePixel;

            return mapUnits;
        }

        private string query(AxMapControl mapControl, IFeatureLayer featureLayer, IGeometry geometry, string fieldName)
        {
            mapControl.Map.ClearSelection();

            IFeatureClass featureClass = featureLayer.FeatureClass;
            if (featureClass == null)
            {
                return null;
            }

            // 初始化空间过滤器
            ISpatialFilter spatialFilter = new SpatialFilterClass();
            spatialFilter.Geometry = geometry;

            // 根据图层类型选择缓冲方式
            switch (featureClass.ShapeType)
            {
                case esriGeometryType.esriGeometryPoint:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelCrosses;
                    break;
                case esriGeometryType.esriGeometryPolygon:
                    spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    break;
            }

            // 定义空间过滤器的空间字段
            spatialFilter.GeometryField = featureClass.ShapeFieldName;

            // 利用要素过滤器查询要素
            IQueryFilter queryFilter = spatialFilter as IQueryFilter;
            IFeatureCursor featureCursor = featureLayer.Search(queryFilter, true);
            IFeature feature = featureCursor.NextFeature();

            string szNames = null;
            while (feature != null)
            {
                // 选择指定要素
                int fieldIndex = feature.Fields.FindField(fieldName);
                // 获取要素名称
                szNames += feature.get_Value(fieldIndex) + "/";

                mapControl.Map.SelectFeature(featureLayer as ILayer, feature);
                mapControl.ActiveView.Refresh();
                feature = featureCursor.NextFeature();
            }
            return szNames;
        }

        /// <summary>
        /// 从TocControl（图层管理器）中获取当前选中的矢量图层（IFeatureLayer）
        /// </summary>
        /// <returns>选中的矢量图层，若未选中或选中非矢量图层则返回null</returns>
        private IFeatureLayer getSelectedFeatureLayer()
        {
            // 初始化所有输出参数
            esriTOCControlItem itemType = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap basicMap = null;
            ILayer layer = null;
            object unk = null;
            object data = null;

            // 调用GetSelectedItem时，传入所有必需的ref参数
            this.axTOCControl1.GetSelectedItem(ref itemType, ref basicMap, ref layer, ref unk, ref data);

            // 判断选中项是否为图层且为矢量图层
            if (itemType == esriTOCControlItem.esriTOCControlItemLayer && layer is IFeatureLayer)
            {
                return layer as IFeatureLayer;
            }

            return null;
        }


        private void PointQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 1;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void LineQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 2;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void CircleQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 3;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void RectangleQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer selectedFeatureLayer = getSelectedFeatureLayer();
            if (selectedFeatureLayer != null)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(selectedFeatureLayer);
                if (fieldSelectDialog.ShowDialog() == DialogResult.OK)
                {
                    m_iMouseFlag = 4;
                    m_szFieldName = fieldSelectDialog.selectFieldName();
                    this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        /// <summary>
        /// “关闭查询”菜单项点击事件响应
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void closeQueryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 1. 检查地图当前是否有选中要素，若有则清除选择并刷新地图
            if (this.axMapControl1.Map.SelectionCount > 0)
            {
                this.axMapControl1.Map.ClearSelection(); // 清除地图上所有选中的要素
                this.axMapControl1.ActiveView.Refresh(); // 刷新地图视图，使清除效果生效
            }

            // 2. 将鼠标指针恢复为默认样式（非十字准星）
            this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;

            // 3. 重置鼠标操作标记，终止查询状态
            this.m_iMouseFlag = 0;
        }

        // 修正后的像素转地理距离函数
        private double ConvertPixelToMapUnits(IActiveView activeView, double pixelUnits)
        {
            tagRECT deviceFrame = activeView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();
            double screenWidth = deviceFrame.right - deviceFrame.left;
            IEnvelope envelope = activeView.Extent;
            double mapWidth = envelope.Width;
            double pixelPerMapUnit = screenWidth / mapWidth;
            return pixelUnits / pixelPerMapUnit;
        }

        private void AxMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (m_iMouseFlag == 0)
            {
                return;
            }

            string szNames = "字段" + m_szFieldName + "的值查询：";
            if (m_iMouseFlag == 1)
            {
                // 获取视图范围
                IActiveView activeView = this.axMapControl1.ActiveView;
                // 获取鼠标点击屏幕坐标
                IPoint point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
                // 屏幕距离转换为地图距离
                double dLength = convertPixelToMapUnits(activeView, 2);

                // 根据缓冲区半径生成空间过滤器
                ITopologicalOperator topoOperator = point as ITopologicalOperator;
                IGeometry geoBuffer = topoOperator.Buffer(dLength);

                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), geoBuffer, m_szFieldName);
            }
            else if (m_iMouseFlag == 2)//线查询
            {
                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), this.axMapControl1.TrackLine(), m_szFieldName);
            }
            else if (m_iMouseFlag == 3)//矩形查询
            {
                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), this.axMapControl1.TrackRectangle(), m_szFieldName);
            }
            else if (m_iMouseFlag == 4)//圆查询
            {
                szNames += query(this.axMapControl1, getSelectedFeatureLayer(), this.axMapControl1.TrackCircle(), m_szFieldName);
            }

            MessageBox.Show(szNames);
        }

        private DataTable dtAttribute = new DataTable();




        private DataTable QueryFeatures(AxMapControl mapControl, IFeatureLayer featureLayer, IGeometry geometry)
        {
            dtAttribute.Clear();
            dtAttribute.Columns.Clear();

            IFeatureClass featureClass = featureLayer.FeatureClass;
            if (featureClass == null)
            {
                return dtAttribute;
            }

            // 创建 DataTable 列，对应要素类的字段
            for (int i = 0; i < featureClass.Fields.FieldCount; i++)
            {
                IField field = featureClass.Fields.get_Field(i);
                dtAttribute.Columns.Add(field.Name, Type.GetType("System.Object"));
            }

            // 执行空间查询
            ISpatialFilter spatialFilter = new SpatialFilterClass();
            spatialFilter.Geometry = geometry;
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            spatialFilter.GeometryField = featureClass.ShapeFieldName;

            IFeatureCursor featureCursor = featureClass.Search(spatialFilter, false);
            // 此处是关键位置，调用 NextFeature() 方法获取要素
            IFeature feature = featureCursor.NextFeature();

            while (feature != null)
            {
                DataRow row = dtAttribute.NewRow();
                for (int i = 0; i < featureClass.Fields.FieldCount; i++)
                {
                    row[i] = feature.get_Value(i);
                }
                dtAttribute.Rows.Add(row);
                // 循环中再次调用 NextFeature() 获取下一个要素
                feature = featureCursor.NextFeature();
            }

            // 释放资源
            System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);

            return dtAttribute;
        }



        private void AxMapControl1_OnSelectionChanged(object sender, EventArgs e)
        {
            IFeatureLayer featureLayer = getSelectedFeatureLayer();
            if (featureLayer == null)
            {
                dtAttribute.Clear();
                dgvAttribute.DataSource = null;
                return;
            }

            IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
            if (featureSelection == null)
            {
                return;
            }

            ISelectionSet selectionSet = featureSelection.SelectionSet;
            if (selectionSet == null || selectionSet.Count == 0)
            {
                dtAttribute.Clear();
                dgvAttribute.DataSource = null;
                return;
            }

            // 关键修复：先清空DataTable的列，避免重复添加
            dtAttribute.Columns.Clear();
            dtAttribute.Rows.Clear();

            IFeatureClass featureClass = featureLayer.FeatureClass;
            for (int i = 0; i < featureClass.Fields.FieldCount; i++)
            {
                IField field = featureClass.Fields.get_Field(i);
                dtAttribute.Columns.Add(field.Name, Type.GetType("System.Object"));
            }

            ICursor cursor = null;
            selectionSet.Search(null, false, out cursor);
            IFeatureCursor featureCursor = cursor as IFeatureCursor;
            IFeature feature = featureCursor.NextFeature();

            while (feature != null)
            {
                DataRow row = dtAttribute.NewRow();
                for (int i = 0; i < featureClass.Fields.FieldCount; i++)
                {
                    row[i] = feature.get_Value(i);
                }
                dtAttribute.Rows.Add(row);
                feature = featureCursor.NextFeature();
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(cursor);

            dgvAttribute.DataSource = dtAttribute;
            tabControl1.SelectedTab = tabPageAttribute;
        }
    }
}
